﻿<!DOCTYPE html>
<html lang="zh-CN">
        <link rel="icon" href="../images/dzlogo.png">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>睡眠质量评价报告</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: "Microsoft YaHei", "SimHei", sans-serif;
        }
        
        body {
            color: #333;
            line-height: 1.5;
            padding: 20px;
            background-color: #f5f5f5;
        }
        
        .report-container {
            max-width: 1000px;
            margin: 0 auto;
            background: white;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
            border-radius: 5px;
            overflow: hidden;
            position: relative;
        }
        
        .header {
            background: linear-gradient(135deg, #1a6dcc 0%, #0d4d9c 100%);
            color: white;
            padding: 15px 20px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            position: relative;
        }

        /* 确保小标题在屏幕显示时也有蓝色背景 */
        .header.small {
            background: linear-gradient(135deg, #1a6dcc 0%, #0d4d9c 100%);
            color: white;
            padding: 8px 12px;
            border-bottom: 1px solid #e6eefc;
        }

        .header.small .title {
            font-size: 16px;
            font-weight: 700;
            color: white;
        }
    /* Ensure logo is visible in the compact/small header as well */
    .header.small .logo { display: inline-block; height:40px; width:auto; margin-right:10px; }
        
        .logo-container {
            display: flex;
            align-items: center;
        }
        
        .logo {
            height: 50px;
            width: auto;
            margin-right: 15px;
        }
        
        .title {
            font-size: 20px;
            font-weight: bold;
        }
        
        .report-info {
            font-size: 14px;
            text-align: right;
        }
        
        .patient-info {
            padding: 15px 20px;
            background-color: #f0f7ff;
            border-bottom: 1px solid #ddd;
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 10px;
        }
        
        .info-item {
            display: flex;
        }
        
        .info-label {
            font-weight: bold;
            min-width: 80px;
        }
        
        .page {
            padding: 20px;
            position: relative;
        }
        
        .section-title {
            font-size: 18px;
            font-weight: 700;
            margin: 18px 0 12px;
            color: #0d4d9c;
            position: relative;
            padding-bottom: 6px;
        }


        /* 恢复标题下的蓝色分割线 - 确保在屏幕显示时也可见 */
        .section-title {
            font-size: 18px;
            font-weight: 700;
            margin: 18px 0 12px;
            color: #0d4d9c;
            position: relative;
            padding-bottom: 6px;
        }

        .section-title::after {
            content: '';
            display: block;
            width: 100%;
            height: 3px;
            background: linear-gradient(90deg, #1a6dcc 0%, #3b82f6 100%);
            border-radius: 2px;
            margin-top: 6px;
        }
        
        .summary-box {
            background-color: #fafbff;
            /* 改为内置短横强调条，避免跨页或过长的线条 */
            padding: 14px 16px;
            margin: 10px 0;
            border-radius: 8px;
            border: 1px solid rgba(26,109,204,0.06);
            position: relative;
        }

        /* 隐藏之前的 summary-box 装饰条，改用醒目的圆形序号 */
        .summary-box::before{ display: none; }

        .summary-box ul {
            margin: 12px 0 0 0;
            padding-left: 0;
        }

        .summary-box ul li {
            margin: 10px 0;
            line-height: 1.5;
            position: relative;
            padding-left: 24px;
            color: #163a66;
        }
        /* 美化 summary-box 内的无序列表（医嘱） */
        .summary-box ul {
            list-style: none;
            padding-left: 0;
            margin: 8px 0 0 0;
        }

        .summary-box ul li {
            position: relative;
            padding-left: 24px;
            margin: 8px 0;
            color: #163a66;
        }

        .summary-box ul li::before{
            content: '';
            position: absolute;
            left: 4px;
            top: 8px;
            width: 10px;
            height: 10px;
            background: linear-gradient(180deg,#1a6dcc,#3b82f6);
            border-radius: 50%;
            box-shadow: 0 1px 2px rgba(16,24,40,0.04);
        }
        
        /* 修改为竖列排版 */
        .warning-list {
            display: flex;
            flex-direction: column;
            gap: 10px;
            margin: 15px 0;
        }
        
        .warning-item {
            display: flex;
            align-items: center;
            padding: 8px;
            background-color: #fff9f9;
            border-radius: 4px;
            border-left: 3px solid #e74c3c;
        }
        
        .warning-item.no-warning {
            background-color: #f0fff0;
            border-left: 3px solid #2ecc71;
        }
        
        .score-table {
            width: 100%;
            border-collapse: collapse;
            margin: 15px 0;
            box-shadow: 0 1px 3px rgba(0,0,0,0.08);
        }
        .merged-score-table .merged-title {
            font-size: 1.3em;
            font-weight: 600;
            text-align: center;
            vertical-align: middle;
            background: #d6f5d6;
            color: #234d23;
            border: 1px solid #b2d8b2;
        }
        .merged-score-table .ai-title {
            background: #fff6d6;
            color: #7a5a1e;
            border: 1px solid #e6d8b2;
        }
        .merged-score-table .score-header {
            background: #b3c7e6;
            color: #234d4d;
            font-weight: 500;
            text-align: center;
            border: 1px solid #a0b3c6;
            white-space: nowrap;
            vertical-align: middle;
        }
        .merged-score-table .score-value {
            background: #e6f2ff;
            color: #234d4d;
            font-size: 1.1em;
            text-align: center;
            border: 1px solid #a0b3c6;
        }
        .score-tip {
            font-size: 13px;
            color: #888;
            margin-top: 4px;
            margin-bottom: 8px;
            text-align: left;
            font-style: italic;
        }
        
        .detail-table {
            width: 100%;
            border-collapse: collapse;
            margin: 15px 0;
            font-size: 14px;
        }
        
        .detail-table th, .detail-table td {
            padding: 8px 10px;
            border: 1px solid #ddd;
            text-align: left;
        }
        
        .detail-table th {
            background-color: #f0f7ff;
            font-weight: bold;
        }
        
        .detail-table tr:nth-child(even) {
            background-color: #f9f9f9;
        }
        
        .signature-area {
            margin-top: 28px;
            padding-top: 12px;
            /* 用细线代替明显虚线，使页面更干净 */
            border-top: 1px solid rgba(0,0,0,0.06);
            display: flex;
            justify-content: space-between;
            gap: 20px;
            align-items: center;
        }

        .sig-field {
            display:inline-block;
            min-width:220px;
            border-bottom:1px solid rgba(0,0,0,0.12);
            padding-bottom:4px;
            color: rgba(0,0,0,0.6);
        }
        
        .footer {
            text-align: center;
            padding: 10px;
            font-size: 12px;
            color: #666;
            border-top: 1px solid #ddd;
            margin-top: 20px;
        }
        
        .page-number {
            position: absolute;
            bottom: 10px;
            right: 20px;
            font-size: 12px;
            color: #666;
        }
        
        /* 新增页面地址样式 */
        .page-url {
            position: absolute;
            bottom: 10px;
            left: 20px;
            font-size: 12px;
            color: #666;
            /* 打印时隐藏 */
            display: none;
        }

        /* Group sections 3-5: avoid internal page breaks when printing; do NOT force a new page (avoids extra blank pages) */
        @media print {
            .group-3-5 {
                page-break-inside: avoid;
                -webkit-column-break-inside: avoid;
                break-inside: avoid;
            }
        }
        
        @media print {
            @page {
                size: A4;
                margin: 15mm;
            }
            
            body {
                background: white;
                padding: 0;
                margin: 0;
            }
            
            .report-container {
                box-shadow: none;
                border-radius: 0;
                max-width: none;
                margin: 0;
            }

            /* 强制打印时显示所有颜色 */
            * {
                -webkit-print-color-adjust: exact !important;
                print-color-adjust: exact !important;
            }
            
            .header {
                background: #1a6dcc !important;
                -webkit-print-color-adjust: exact;
                print-color-adjust: exact;
            }
            
            /* 打印时调整页面间距，使内容更紧凑 */
            .page {
                padding: 10px;
                margin: 0;
            }
            /* Use page-break-before on subsequent .page elements to avoid a trailing blank page */
            .page + .page {
                page-break-before: always;
            }
            
            .patient-info {
                padding: 10px 15px;
                gap: 5px;
            }
            
            .summary-box {
                margin: 10px 0;
                padding: 10px;
            }

            .page-break {
                page-break-after: always;
                break-after: page;
            }
            
            .warning-list {
                margin: 10px 0;
                gap: 5px;
            }
            
            .warning-item {
                padding: 5px;
            }
            
            .score-table {
                margin: 10px 0;
            }
            
            .score-table th, .score-table td {
                padding: 8px 5px;
            }

            /* 改进合并评分表在打印时的布局，避免单元格溢出和右侧拥挤 */
            .merged-score-table {
                table-layout: fixed !important;
                width: 100% !important;
                box-shadow: none !important;
                font-size: 12px !important;
            }

            .merged-score-table th,
            .merged-score-table td {
                padding: 6px 4px !important;
                word-break: break-word !important;
                overflow-wrap: anywhere !important;
                hyphens: auto;
                white-space: normal !important;
            }

            .merged-score-table .merged-title,
            .merged-score-table .score-header,
            .merged-score-table .score-value {
                white-space: normal !important;
            }
            
            .detail-table {
                margin: 10px 0;
            }
            
            .detail-table th, .detail-table td {
                padding: 6px 8px;
                line-height: 1.6;
                font-size: 13px;
            }
            
            /* 打印时隐藏页面地址 */
            .page-url {
                display: none !important;
            }
        }
        
        /* 屏幕显示时显示页面地址 */
        @media screen {
            .page-url {
                display: block;
            }
        }
        
        /* AI分析报告样式 */
        .ai-analysis-container {
            margin: 20px 0;
            padding: 20px;
            background-color: #f8f9fa;
            border-radius: 8px;
            border-left: 4px solid #1a6dcc;
        }
        
        .ai-analysis-loading {
            display: none;
            text-align: center;
            padding: 20px;
        }
        
        .ai-analysis-loading .loading-text {
            color: #1a6dcc;
            font-size: 16px;
            margin-bottom: 10px;
        }
        
        .loading-progress-bar {
            width: 100%;
            background-color: #e9ecef;
            border-radius: 4px;
            height: 6px;
            margin: 0 auto;
            max-width: 300px;
        }
        
        .loading-progress {
            width: 0%;
            height: 100%;
            background: linear-gradient(90deg, #1a6dcc, #3b82f6);
            border-radius: 4px;
            transition: width 0.3s;
        }
        
        .ai-analysis-content {
            display: none;
            line-height: 1.6;
            color: #333;
        }
        
        .ai-analysis-error {
            display: none;
            color: #dc3545;
            padding: 15px;
            background-color: #f8d7da;
            border-radius: 4px;
        }
        
        .generate-ai-analysis-btn {
            background: linear-gradient(135deg, #1a6dcc 0%, #0d4d9c 100%);
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 500;
            transition: all 0.3s;
            margin-top: 10px;
        }
        
        .generate-ai-analysis-btn:hover {
            opacity: 0.9;
        }
        
        .generate-ai-analysis-btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
        }
        
        .ai-analysis-content h4 {
            color: #1a6dcc;
            margin-bottom: 10px;
        }
        
        .ai-analysis-content ul {
            padding-left: 20px;
        }
        
        .ai-analysis-content li {
            margin-bottom: 8px;
        }
    </style>
</head>
<body>
    <div class="report-container">
        <!-- 第1页 -->
        <div class="page">
        <div class="header small">  
                <div class="logo-container">
                    <!-- 这里放置logo图片 -->
                    <img src="../images/pro.png" alt="生命潮" class="logo">
                    <div class="title">生命潮@BBS睡眠质量主客观双百分联合评价报告</div>
                </div>
                <div class="report-info">
                    报告编号: 119953<br>
                    
                </div>
            </div>
            
            <h2 class="section-title">个人信息</h2>
            <div class="patient-info">
                <div class="info-item"><span class="info-label">管理师/医生:  海大力</div>
                <div class="info-item"><span class="info-label">姓名: 海大力</div>
                <div class="info-item"><span class="info-label">性别: 男</div>
                <div class="info-item"><span class="info-label">年龄: 33</div>
                <div class="info-item"><span class="info-label">身高: 170.0cm</div>
                <div class="info-item"><span class="info-label">体重: 60.0kg</div>
                <div class="info-item"><span class="info-label">测评时长: 1小时14分23秒</div>
                <div class="info-item"><span class="info-label">科室: 北京协和医院睡眠科室</div>
            </div>

            <h2 class="section-title">危险项提示</h2>
            
            <!-- 修改为竖列排版 -->
            <div class="warning-list">
                <div class="warning-item no-warning">
                    <span>心电图QRS波群混乱或消失: 有</span>
                </div>
                <div class="warning-item no-warning">
                    <span>室颤/房颤: 有</span>
                </div>
                <div class="warning-item no-warning">
                    <span>呼吸暂停持续时间≥40秒，或整晚累计时间≥30分钟: 有</span>
                </div>
                <div class="warning-item no-warning">
                    <span>呼吸阻滞持续时间≥30分钟，或整晚累计时间≥90分钟: 有</span>
                </div>
                <div class="warning-item no-warning">
                    <span>SpO2≤85%: 有</span>
                </div>
                <div class="warning-item no-warning">
                    <span>行走梦游: 有</span>
                </div>
            </div>

            <div class="section-title">医嘱</div>
            <div class="summary-box">
                <p>根据评估结果，建议您：</p>
                <ul>
                    <li>建立规律的睡眠时间表，尽量每天同一时间上床和起床</li>
                    <li>睡前避免使用电子设备，创造安静、黑暗的睡眠环境</li>
                    <li>避免在睡前摄入咖啡因或大量食物</li>
                    <li>如有持续睡眠问题，建议咨询专业睡眠医生</li>
                </ul>
            </div>

            <h2 class="section-title">睡眠质量评分</h2>
            <table class="score-table merged-score-table">
                <tr>
                    <td class="merged-title self-title" rowspan="2">BBS-自评量表</td>
                    <td class="score-header">总得分（满分100）</td>
                    <td class="score-header">睡眠效率（满分6）</td>
                    <td class="score-header">睡眠质量（满分46）</td>
                    <td class="score-header">睡眠干扰（满分48）</td>
                </tr>
                <tr>
                    <td class="score-value">61.5</td>
                    <td class="score-value">4</td>
                    <td class="score-value">20</td>
                    <td class="score-value">37.5</td>
                </tr>
                <tr>
                    <td class="merged-title ai-title" rowspan="2">BBS-AI评估量表</td>
                    <td class="score-header">总得分（满分100）</td>
                    <td class="score-header">睡眠风险（满分34）</td>
                    <td class="score-header">睡眠事件（满分32）</td>
                    <td class="score-header">睡眠概况（满分34）</td>
                </tr>
                <tr>
                    <td class="score-value">46</td>
                    <td class="score-value">29</td>
                    <td class="score-value">11</td>
                    <td class="score-value">6</td>
                </tr>
            </table>
            <div>
            <div>

        <div class="page">
        <div class="header small">
                <div class="logo-container">
                    <img src="../images/dzlogo.png" alt="生命潮" class="logo">
                    <div class="title">BBS 睡眠质量主客观双百分评价报告一：自评报告</div>
                </div>
                <div class="report-info">
                    报告编号: 119953<br>
                </div>
            </div>
            
            <div class="section-title">一：自评报告</div>
            
            <table class="detail-table" id="self-report-table">
                <thead>
                    <tr>
                        <th>评价维度</th>
                        <th>自评条目</th>
                        <th>自评</th>
                        <th>等级</th>
                        <th>得分</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td rowspan="2">睡眠效率</td>
                        <td>1. 实际睡者时长（小时）</td>
                        <td>1</td>
                        <td>优</td>
                        <td>4</td>
                    </tr>
                    <tr>
                        <td>2. 熄灯后，到达睡眠的时长（分钟）</td>
                        <td>1</td>
                        <td>98%（效率值）</td>
                        <td></td>
                    </tr>
                    <tr>
                        <td rowspan="5">睡眠质量</td>
                        <td>3. 睡眠药物</td>
                        <td>1个单位剂量</td>
                        <td>良</td>
                        <td>6</td>
                    </tr>
                    <tr>
                        <td>4. 醒后疲劳或不适应</td>
                        <td>非常疲劳或不适</td>
                        <td>很差</td>
                        <td>4</td>
                    </tr>
                    <tr>
                        <td>5. 睡眠中途醒来的次数</td>
                        <td>3次及以上</td>
                        <td>很差</td>
                        <td>4</td>
                    </tr>
                    <tr>
                        <td>6. 当晚醒后再放入眠的难易程度</td>
                        <td>无法</td>
                        <td>很差</td>
                        <td>4</td>
                    </tr>
                    <tr>
                        <td>7. 昨晚睡的怎样</td>
                        <td>很差</td>
                        <td>很差</td>
                        <td>2</td>
                    </tr>
                    <tr>
                        <td rowspan="6">睡眠干扰</td>
                        <td>8. 起夜次数</td>
                        <td>3次以上</td>
                        <td>很差</td>
                        <td>2</td>
                    </tr>
                    <tr>
                        <td>9. 做梦情况</td>
                        <td>有噩梦</td>
                        <td>很差</td>
                        <td>1.5</td>
                    </tr>
                    <tr>
                        <td>10. 呼吸不畅、咳嗽、打鼾、磨牙</td>
                        <td>无上述情况</td>
                        <td>优</td>
                        <td>8</td>
                    </tr>
                    <tr>
                        <td>11. 睡眠中睡眠状态不适应、怠慢、轻度、低血压、头痛等症状</td>
                        <td>无上述情况</td>
                        <td>优</td>
                        <td>10</td>
                    </tr>
                    <tr>
                        <td>12. 睡眠环境的影响、偏好、过度、严重、误导、厌食或肥胖者</td>
                        <td>无上述情况</td>
                        <td>优</td>
                        <td>8</td>
                    </tr>
                    <tr>
                        <td>13. 睡前的饥饿或饱腹状况</td>
                        <td>无上述情况</td>
                        <td>优</td>
                        <td>8</td>
                    </tr>
                    <tr>
                        <td colspan="4" style="text-align: right; font-weight: bold;">总分</td>
                        <td style="font-weight: bold;">61.5</td>
                    </tr>
                    <tr>
                        <td colspan="5" style="text-align: center; font-weight: bold;">一般</td>
                    </tr>
                </tbody>
            </table>
    
            <div class="footer">
                
            </div>
            <div class="page-number">第2页，共4页</div>
        </div>
        
        <div style="page-break-before: always;"></div>
        
        <!-- 第3页 - AI评估报告 -->
        <div class="page">
        <div class="header small">
                <div class="logo-container">
                    <img src="../images/dzlogo.png" alt="生命潮" class="logo">
                    <div class="title">BBS 睡眠质量主客观双百分评价报告二：AI 评估报告</div>
                </div>
                <div class="report-info">
                    报告编号: 119953<br>
                </div>
            </div>
            
            <div class="section-title">二：AI 评估报告</div>
            
            <table class="detail-table" id="ai-report-table">
                <thead>
                    <tr>
                        <th>分析维度</th>
                        <th>分析条目</th>
                        <th>判断</th>
                        <th>等级</th>
                        <th>得分</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td rowspan="6">睡眠风险</td>
                        <td>心电图ST段改变</td>
                        <td>无</td>
                        <td>优</td>
                        <td>4</td>
                    </tr>
                    <tr>
                        <td>心律失常</td>
                        <td>无心律失常</td>
                        <td>优</td>
                        <td>6</td>
                    </tr>
                    <tr>
                        <td>呼吸暂停</td>
                        <td>10秒<持续时间<20秒，或整晚累计时间<5分钟</td>
                        <td>良</td>
                        <td>6</td>
                    </tr>
                    <tr>
                        <td>呼吸阻滞：慢性缺氧</td>
                        <td>持续时间≤5分钟，或整晚累计时间<10分钟</td>
                        <td>良</td>
                        <td>4</td>
                    </tr>
                    <tr>
                        <td>血氧饱和度</td>
                        <td>Sp02-97%-95%</td>
                        <td>良</td>
                        <td>3</td>
                    </tr>
                    <tr>
                        <td>意识障碍风险</td>
                        <td>无</td>
                        <td>优</td>
                        <td>6</td>
                    </tr>
                    <tr>
                        <td rowspan="5">睡眠事件</td>
                        <td>翻身频次</td>
                        <td>每小时≥10次，4小时<1次</td>
                        <td>很差</td>
                        <td>2</td>
                    </tr>
                    <tr>
                        <td>翻身模式</td>
                        <td>3级复式翻身>4次以上</td>
                        <td>很差</td>
                        <td>2</td>
                    </tr>
                    <tr>
                        <td>躯体休眠</td>
                        <td>每小时4-9次</td>
                        <td>差</td>
                        <td>4</td>
                    </tr>
                    <tr>
                        <td>睡眠姿态</td>
                        <td>>45度角坐睡，整晚>45分钟</td>
                        <td>很差</td>
                        <td>1</td>
                    </tr>
                    <tr>
                        <td>睡眠态焦虑水平</td>
                        <td>60≤SDNN<100</td>
                        <td>差</td>
                        <td>2</td>
                    </tr>
                    <tr>
                        <td rowspan="4">睡眠概况</td>
                        <td>入眠时间</td>
                        <td>>30分钟</td>
                        <td>很差</td>
                        <td>1</td>
                    </tr>
                    <tr>
                        <td>睡眠时长</td>
                        <td>整晚无睡眠</td>
                        <td>非常差</td>
                        <td>0</td>
                    </tr>
                    <tr>
                        <td>起夜次数</td>
                        <td>2次</td>
                        <td>差</td>
                        <td>4</td>
                    </tr>
                    <tr>
                        <td>深度睡眠时长</td>
                        <td>深度睡眠时长占睡眠时长比<5%>
                        <td>很差</td>
                        <td>1</td>
                    </tr>
                    <tr>
                        <td colspan="4" style="text-align: right; font-weight: bold;">总分</td>
                        <td style="font-weight: bold;">46</td>
                    </tr>
                    <tr>
                        <td colspan="5" style="text-align: center; font-weight: bold;">差</td>
                    </tr>
                </tbody>
            </table>
            
            <div class="footer">
                本报告仅供健康建议参考，具体诊断请咨询专业医生。
            </div>
            <div class="page-number">第3页，共4页</div>
        </div>
        
        <div style="page-break-before: always;"></div>
        
        <!-- 第4页 - AI智能分析总结 -->
        <div class="page">
        <div class="header small">
                <div class="logo-container">
                    <img src="../images/dzlogo.png" alt="生命潮" class="logo">
                    <div class="title">BBS 睡眠质量主客观双百分评价报告三：AI智能分析总结</div>
                </div>
                <div class="report-info">
                    报告编号: 119953<br>
                </div>
            </div>
            
            <!-- AI报告总结部分 -->
            <div class="section-title">三：AI智能分析总结</div>
            <div class="ai-analysis-container">
                <div class="ai-analysis-loading">
                    <div class="loading-text">🤖 AI正在分析您的睡眠数据...</div>
                    <div class="loading-progress-bar">
                        <div class="loading-progress" id="loading-progress"></div>
                    </div>
                </div>
                <div class="ai-analysis-content" id="ai-analysis-content">
                </div>
                <div class="ai-analysis-error" id="ai-analysis-error">
                </div>
                <button class="generate-ai-analysis-btn" id="generate-ai-analysis" onclick="generateAIAnalysis()">
                    生成AI智能分析总结
                </button>
            </div>
            
            <div class="signature-area">
                <div>
                    <p>医生（签字）： <span class="sig-field"></span></p>
                </div>
                <div>
                    <p>日期（签字）： <span class="sig-field"></span></p>
                </div>
            </div>
            <div class="page-number">第4页，共4页</div>
        </div>
    </div>

    <script>
        // 收集报告数据的函数
        function collectReportData() {
            // 收集个人信息
            const patientInfo = {
                name: "海大力",
                gender: "男",
                age: 33,
                height: 170.0,
                weight: 60.0
            };
            
            // 收集自评报告数据
            const selfReportData = [];
            const selfReportTable = document.getElementById('self-report-table');
            if (selfReportTable) {
                const rows = selfReportTable.querySelectorAll('tbody tr');
                rows.forEach(row => {
                    const cells = row.querySelectorAll('td');
                    if (cells.length >= 5) {
                        selfReportData.push({
                            dimension: cells[0].textContent.trim(),
                            item: cells[1].textContent.trim(),
                            rating: cells[2].textContent.trim(),
                            level: cells[3].textContent.trim(),
                            score: cells[4].textContent.trim()
                        });
                    }
                });
            }
            
            // 收集AI评估报告数据
            const aiReportData = [];
            const aiReportTable = document.getElementById('ai-report-table');
            if (aiReportTable) {
                const rows = aiReportTable.querySelectorAll('tbody tr');
                rows.forEach(row => {
                    const cells = row.querySelectorAll('td');
                    if (cells.length >= 5) {
                        aiReportData.push({
                            dimension: cells[0].textContent.trim(),
                            item: cells[1].textContent.trim(),
                            judgment: cells[2].textContent.trim(),
                            level: cells[3].textContent.trim(),
                            score: cells[4].textContent.trim()
                        });
                    }
                });
            }
            
            // 收集评分数据
            const scoreData = {
                selfTotal: 61.5,
                aiTotal: 46
            };
            
            // 收集危险项提示数据
            const warningData = [];
            const warningItems = document.querySelectorAll('.warning-item');
            warningItems.forEach(item => {
                const text = item.textContent.trim();
                // 只收集有警告的项（非"无"的项）
                if (text && !text.includes(': 无')) {
                    warningData.push(text);
                }
            });
            
            return {
                patientInfo,
                selfReportData,
                aiReportData,
                scoreData,
                warningData
            };
        }
        
        // 生成AI分析总结的函数
        async function generateAIAnalysis() {
            // 获取所有AI分析按钮和容器
            const buttons = document.querySelectorAll('.generate-ai-analysis-btn');
            const loadingIndicators = document.querySelectorAll('.ai-analysis-loading');
            const contentContainers = document.querySelectorAll('.ai-analysis-content');
            const errorContainers = document.querySelectorAll('.ai-analysis-error');
            
            // 禁用所有按钮并显示加载状态
            buttons.forEach(button => {
                button.disabled = true;
                button.textContent = '生成中...';
            });
            
            loadingIndicators.forEach(indicator => {
                indicator.style.display = 'block';
            });
            
            contentContainers.forEach(container => {
                container.style.display = 'none';
            });
            
            errorContainers.forEach(container => {
                container.style.display = 'none';
            });
            
            // 模拟进度条动画 - 更真实的进度模拟
            const progressBars = document.querySelectorAll('.loading-progress');
            let progress = 0;
            
            // 使用非线性进度增加，开始慢，中间快，最后慢
            const interval = setInterval(() => {
                if (progress < 30) {
                    // 初始阶段较慢
                    progress += 1;
                } else if (progress < 70) {
                    // 中间阶段较快
                    progress += 3;
                } else if (progress < 90) {
                    // 后期较慢
                    progress += 1;
                } else {
                    // 最后阶段非常慢，模拟AI处理时间
                    progress += 0.5;
                }
                
                progressBars.forEach(bar => {
                    bar.style.width = `${Math.min(progress, 100)}%`;
                });
                
                if (progress >= 100) {
                    clearInterval(interval);
                }
            }, 200); // 降低更新频率，让进度条变化更平滑
            
            try {
                // 收集报告数据
                const reportData = collectReportData();
                
                // 构造发送给AI的提示
                const aiPrompt = `请根据以下睡眠质量评估报告数据，生成一份综合性的AI分析报告：
                
                个人信息：
                姓名：${reportData.patientInfo.name}
                性别：${reportData.patientInfo.gender}
                年龄：${reportData.patientInfo.age}岁
                身高：${reportData.patientInfo.height}cm
                体重：${reportData.patientInfo.weight}kg

                自评报告总分：${reportData.scoreData.selfTotal}
                AI评估报告总分：${reportData.scoreData.aiTotal}
                
                危险项提示：
                ${reportData.warningData.length > 0 ? 
                  reportData.warningData.map(item => `- ${item}`).join('\n') : 
                  '无明显危险项'}

                自评报告详情：
                ${reportData.selfReportData.map(item => 
                    `- ${item.dimension} - ${item.item}：评分${item.score}，等级${item.level}，评价${item.rating}`
                ).join('\n')}

                AI评估报告详情：
                ${reportData.aiReportData.map(item => 
                    `- ${item.dimension} - ${item.item}：评分${item.score}，等级${item.level}，判断${item.judgment}`
                ).join('\n')}

                请结合以上数据，生成一份综合性分析报告，包含以下内容：
                1. 整体睡眠质量评估
                2. 主要问题识别
                3. 改善建议
                4. 需要关注的风险点

                请特别关注危险项提示中的内容，如果存在异常项，请在风险点分析中重点说明。

                请用中文回复，语言简洁明了，便于医生和患者理解。按照以下格式输出：
                一、整体睡眠质量评估
                [内容]

                二、主要问题识别
                [内容]

                三、改善建议
                [内容]`;
                
                // 调用AI API生成分析报告
                const aiResponse = await callAIAPI(aiPrompt);
                displayAIAnalysis(aiResponse);
            } catch (error) {
                console.error('AI分析失败:', error);
                displayAIError(`AI分析失败，请稍后重试 (${error.message})`);
            } finally {
                clearInterval(interval);
                // 恢复按钮状态
                buttons.forEach(button => {
                    button.disabled = false;
                    button.textContent = '生成AI智能分析总结';
                });
                
                loadingIndicators.forEach(indicator => {
                    indicator.style.display = 'none';
                });
            }
        }
        
        // 显示AI分析结果
        function displayAIAnalysis(content) {
            const contentContainers = document.querySelectorAll('.ai-analysis-content');
            contentContainers.forEach(container => {
                // 将Markdown格式的标题转换为HTML格式
                let formattedContent = content;
                formattedContent = formattedContent.replace(/### (.*?)(\n|$)/g, '<h4>$1</h4>');
                formattedContent = formattedContent.replace(/一、(.*?)(\n|$)/g, '<h5>一、$1</h5>');
                formattedContent = formattedContent.replace(/二、(.*?)(\n|$)/g, '<h5>二、$1</h5>');
                formattedContent = formattedContent.replace(/三、(.*?)(\n|$)/g, '<h5>三、$1</h5>');
                formattedContent = formattedContent.replace(/四、(.*?)(\n|$)/g, '<h5>四、$1</h5>');
                formattedContent = formattedContent.replace(/\n\n/g, '</p><p>');
                formattedContent = formattedContent.replace(/\n/g, '<br>');
                formattedContent = '<p>' + formattedContent + '</p>';
                
                container.innerHTML = formattedContent;
                container.style.display = 'block';
            });
        }
        
        // 显示错误信息
        function displayAIError(errorMessage) {
            const errorContainers = document.querySelectorAll('.ai-analysis-error');
            errorContainers.forEach(container => {
                // 根据错误类型提供友好的错误信息
                let friendlyMessage = errorMessage;
                
                if (errorMessage.includes('504') || errorMessage.includes('timeout') || errorMessage.includes('超时')) {
                    friendlyMessage = 'AI服务响应超时，请稍后重试。系统会自动重试，您也可以手动点击按钮重新生成。';
                } else if (errorMessage.includes('Failed to fetch') || errorMessage.includes('网络')) {
                    friendlyMessage = '网络连接异常，请检查网络后重试。';
                } else if (errorMessage.includes('API密钥')) {
                    friendlyMessage = 'AI服务配置错误，请联系管理员检查API密钥配置。';
                }
                
                container.textContent = friendlyMessage;
                container.style.display = 'block';
            });
        }
        
        // 调用AI API的函数
        async function callAIAPI(prompt) {
            // 检查是否已存在AI聊天组件配置
            if (typeof window.AI_CHAT_CONFIG === 'undefined') {
                // 如果没有配置，尝试加载配置
                try {
                    await loadAIConfig();
                } catch (e) {
                    console.warn('无法加载AI配置，使用默认配置');
                }
            }
            
            // 获取配置或使用默认值
            const config = window.AI_CHAT_CONFIG || {
                functionUrl: '/.netlify/functions/chat',
                model: 'Qwen/Qwen3-8B'
            };
            
            // 构建消息历史
            const messages = [
                {
                    role: 'system',
                    content: '你是一个专业的睡眠健康专家，能够根据睡眠评估数据提供专业的分析和建议。'
                },
                {
                    role: 'user',
                    content: prompt
                }
            ];
            
            // 确保使用正确的URL路径
            let functionUrl = config.functionUrl;
            if (functionUrl.startsWith('/.netlify/functions/')) {
                // 在本地开发环境中，可能需要使用完整的路径
                if (window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1') {
                    functionUrl = `http://localhost:8888${functionUrl}`;
                }
            }
            
            // 超时与重试设置（参考ai-chat.js中的稳定实现）
            const timeoutMs = 30000; // 15s 超时（与ai-chat.js保持一致）
            const maxRetries = 3;    // 最多重试 3 次
            const baseDelay = 1000;   // 初始退避 1000ms（与ai-chat.js保持一致）

            const doRequest = async (attempt) => {
                // 超时控制
                const controller = new AbortController();
                const timer = setTimeout(() => controller.abort(), timeoutMs);

                try {
                    const response = await fetch(functionUrl, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'Accept': 'application/json'
                        },
                        body: JSON.stringify({
                            messages: messages,
                            model: config.model
                        }),
                        signal: controller.signal,
                        // 避免某些浏览器缓存 POST
                        cache: 'no-store'
                    });

                    clearTimeout(timer);

                    if (!response.ok) {
                        const errorText = await response.text().catch(() => '');
                        throw new Error(`AI服务请求失败: ${response.status} ${response.statusText}${errorText ? `\n详细信息: ${errorText}` : ''}`);
                    }

                    // 尝试解析 JSON
                    const data = await response.json();

                    // 结构校验
                    if (data && Array.isArray(data.choices) && data.choices[0] && data.choices[0].message) {
                        return data.choices[0].message.content;
                    }

                    // 兼容部分返回结构
                    if (data && data.message && typeof data.message.content === 'string') {
                        return data.message.content;
                    }

                    throw new Error('AI响应格式不正确');
                } catch (err) {
                    clearTimeout(timer);

                    const isAbort = err?.name === 'AbortError';
                    const isTimeout = /超时|timeout|AbortError/i.test(err?.message || '');
                    const isNetwork = /Failed to fetch|NetworkError|网络|fetch|504/i.test(err?.message || '');

                    // 可重试的错误
                    if ((isAbort || isTimeout || isNetwork) && attempt < maxRetries) {
                        const delay = baseDelay * Math.pow(2, attempt); // 指数退避
                        // 不在前端显示重试信息，直接进行重试
                        await new Promise(r => setTimeout(r, delay));
                        return doRequest(attempt + 1);
                    }

                    // 其他错误或超过重试次数
                    throw new Error(`调用AI失败: ${err.message}`);
                }
            };

            return doRequest(0);
        }
        
        // 加载AI配置的函数
        async function loadAIConfig() {
            return new Promise((resolve, reject) => {
                const script = document.createElement('script');
                script.src = '../ai-chat-config.js';
                script.onload = resolve;
                script.onerror = reject;
                document.head.appendChild(script);
            });
        }
        
        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 如果页面中没有AI_CHAT_CONFIG，尝试加载
            if (typeof window.AI_CHAT_CONFIG === 'undefined') {
                loadAIConfig().catch(e => {
                    console.warn('AI配置加载失败:', e);
                });
            }
        });
    </script>
</body>
</html>